<template>
  <div id="personal">
    <div class="changeavatar">
      <img :src="avatarUrl">
      <Upload action="//jsonplaceholder.typicode.com/posts/"
              :format="['jpg','jpeg','png']"
              :max-size="2048"
              :on-format-error="handleFormatError"
              :on-exceeded-size="handleMaxSize"
              :before-upload="handleBeforeUpload">
        <Button type="primary">修改头像</Button>
      </Upload>
      <!--<div class="name-role">
        <h3>姓名 :</h3>
        <h4>{{name}}</h4>
      </div>
      <div class="name-role">
        <h3>角色 :</h3>
        <h4>{{roleName}}</h4>
      </div>-->
    </div>
    <div class="info">
      <Form ref="formCustom"
            :model="formCustom"
            :rules="ruleCustom"
            :label-width="80">

        <FormItem v-if="userId==3"
                  label="姓名 :"
                  class="regular">
          {{no}}
        </FormItem>
        <FormItem label="姓名 :">
          <h4>{{name}}</h4>
        </FormItem>
        <FormItem label="角色 :">
          <h4>{{roleName}}</h4>
        </FormItem>
        <FormItem label="昵称 :">
          <Input type="text"
                 v-model="formCustom.loginName" readonly="true"></Input>
        </FormItem>
        <FormItem label="学历 :">
          <Input type="text"
                 v-model="formCustom.education" maxlength = "16"></Input>
        </FormItem>
        <FormItem label="专业 :">
          <Input type="text"
                 v-model="formCustom.major" maxlength = "16"></Input>
        </FormItem>
        <FormItem label="单位 :">
          <Input type="text"
                 v-model="formCustom.unit" maxlength = "30"></Input>
        </FormItem>
        <FormItem label="籍贯 :">
          <Input type="text"
                 v-model="formCustom.nativePlace" maxlength = "16"></Input>
        </FormItem>
        <FormItem label="手机 :">
          <Input type="text"
                 v-model="formCustom.mobile" maxlength = "11"></Input>
        </FormItem>
        <FormItem label="固定电话 :">
          <Input type="text"
                 v-model="formCustom.telephone" maxlength = "16"></Input>
        </FormItem>
        <FormItem label="联系邮箱 :">
          <Input type="text"
                 v-model="formCustom.email" maxlength = "64"></Input>
        </FormItem>
        <FormItem label="新设密码 :">
          <Input :type="inputType"
                 :icon="inputIcon"
                 @on-click="showPassword"
                 v-model="formCustom.password" maxlength = "16"></Input>
        </FormItem>
        <FormItem label="确认密码 :"
                  prop="passwdCheck">
          <Input :type="inputType"
                 :icon="inputIcon"
                 @on-click="showPassword"
                 v-model="formCustom.passwdCheck" maxlength = "16"></Input>
        </FormItem>
        <FormItem label="介绍 :" style="width: 100%;">
          <Input type="textarea" :rows="2"
                 v-model="formCustom.introduce" maxlength = "500"></Input>
        </FormItem>

        <FormItem>
          <Button type="primary"
                  @click="handleSubmit('formCustom')">保存修改</Button>
        </FormItem>
      </Form>
    </div>
    <Modal title="头像剪裁"
           v-model="visible2"
           :loading="loading2"
           :mask-closable="false"
           @on-ok="avatarOk">
      <div class="cropper-content"
           v-if="visible2">
        <div class="cropper">
          <vueCropper ref="cropper"
                      :img="previewUrl"
                      :canScale="option.canScale"
                      :fixedNumber="option.fixedNumber"
                      :fixed="option.fixed"
                      :centerBox="false"
                      :autoCrop="true"
                      :canMove="false"
                      :mode="option.mode"
                      @realTime="realTime"></vueCropper>
        </div>
        <div :style="previewStyle1">
          <div :style="previews.div">
            <img :src="previews.url"
                 :style="previews.img">
          </div>
        </div>
      </div>
    </Modal>
  </div>
</template>
<script>
import { VueCropper } from 'vue-cropper'
import { uploadPhoto, updateUser } from '@/api/management.js'
import { mapState, mapGetters, mapMutations, mapActions } from 'vuex'
export default {
  data () {
    const validatePass = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('Please enter your password'))
      } else {
        if (this.formCustom.passwdCheck !== '') {
          // 对第二个密码框单独验证
          this.$refs.formCustom.validateField('passwdCheck')
        }
        callback()
      }
    }
    const validatePassCheck = (rule, value, callback) => {
      // if (value === '') {
      //   callback(new Error('Please enter your password again'))
      // } else
      if (value !== this.formCustom.password) {
        callback(new Error('The two input passwords do not match!'))
      } else {
        callback()
      }
    }
    const validateAge = (rule, value, callback) => {
      if (!value) {
        return callback(new Error('Age cannot be empty'))
      }
      // 模拟异步验证效果
      setTimeout(() => {
        if (!Number.isInteger(value)) {
          callback(new Error('Please enter a numeric value'))
        } else {
          if (value < 18) {
            callback(new Error('Must be over 18 years of age'))
          } else {
            callback()
          }
        }
      }, 1000)
    }

    return {
      formCustom: {
        password: this.password,
        passwdCheck: this.password,
        mobile: this.mobile,
        telephone: this.telephone,
        email: this.email,
        unit: this.unit,
        nativePlace: this.nativePlace,
        major: this.major,
        education: this.education,
        introduce: this.introduce,
        loginName: this.loginName
      },
      ruleCustom: {
        passwd: [{ validator: validatePass, trigger: 'blur' }],
        passwdCheck: [{ validator: validatePassCheck, trigger: 'blur' }],
        age: [{ validator: validateAge, trigger: 'blur' }]
      },
      avatarUrl: '',
      option: {
        img: 'http://img1.vued.vanthink.cn/vued751d13a9cb5376b89cb6719e86f591f3.png',
        canScale: false,
        fixed: true,
        fixedNumber: [1, 1],
        fixedBox: true,
        mode: 'cover'
      },
      visible2: false,
      previewStyle2: '',
      loading2: false,
      previewUrl: '',
      previews: "",
      previewStyle1: '',
      previewStyle2: '',
      uploadList: [],
      inputType: 'password',
      inputIcon: 'md-eye-off'
    }
  },
  components: {
    VueCropper,
  },
  methods: {
    ...mapActions(['getUserInfo']),
    handleSubmit (name) {
      this.$refs[name].validate(valid => {
        if (valid) {
          if (this.uploadList.length > 0) {
            let data = new FormData()
            data.append('loginName', this.userName)
            data.append('mf', this.uploadList[0])
            uploadPhoto(data).then(res => {
              if (res.data && res.data != 'fail') {
                let data = {}
                for (let key in this.formCustom) {
                  if (key !== 'passwdCheck') {
                    data[key] = this.formCustom[key]
                  }
                }
                data['photo'] = res.data
                data['loginName'] = this.userName
                data['roleId'] = this.roleId
                data['roleName'] = this.roleName
                data['no'] = this.no
                data['name'] = this.name
                data['id'] = this.userId
               
                data['education'] = this.formCustom.education
                data['major'] = this.formCustom.major
                data['unit'] = this.formCustom.unit
                data['nativePlace'] = this.formCustom.nativePlace
                data['mobile'] = this.formCustom.mobile
                data['telephone'] = this.formCustom.telephone
                data['email'] = this.formCustom.email
                data['password'] = this.formCustom.password
                data['introduce'] = this.formCustom.introduce

                updateUser(data).then(res => {
                  if (res.data == 'success') {
                    this.$Message.success('修改成功!')
                    window.location.reload();
                  } else {
                    this.$Message.error('修改失败!')
                  }
                })
              }
            })
          } else {
            let data = {}
            for (let key in this.formCustom) {
              if (key !== 'passwdCheck') {
                data[key] = this.formCustom[key]
              }
            }
          
                data['loginName'] = this.userName
                data['roleId'] = this.roleId
                data['roleName'] = this.roleName
                data['no'] = this.no
                data['name'] = this.name
                data['id'] = this.userId
                
                data['education'] = this.formCustom.education
                data['major'] = this.formCustom.major
                data['unit'] = this.formCustom.unit
                data['nativePlace'] = this.formCustom.nativePlace
                data['mobile'] = this.formCustom.mobile
                data['telephone'] = this.formCustom.telephone
                data['email'] = this.formCustom.email
                data['password'] = this.formCustom.password
                data['introduce'] = this.formCustom.introduce

            updateUser(data).then(res => {
              if (res.data == "success") {
                this.getUserInfo().then(res => {
                  this.$Message.success('修改成功!')
                  window.location.reload()
                })
              } else {
                this.$Message.warning('修改失败!')
              }

            })
          }
        }
      })
    },
    handleReset (name) {
      this.$refs[name].resetFields()
    },
    handleFormatError (file) {
      this.$Notice.warning({
        title: 'The file format is incorrect',
        desc:
          'File format of ' +
          file.name +
          ' is incorrect, please select jpg or png.'
      })
    },
    handleMaxSize (file) {
      this.$Notice.warning({
        title: 'Exceeding file size limit',
        desc: 'File  ' + file.name + ' is too large, no more than 2M.'
      })
    },
    handleBeforeUpload (file) {
      if (
        file.type === 'image/png' ||
        file.type === 'image/jpg' ||
        file.type === 'image/jpeg'
      ) {
        let reader = new FileReader()
        reader.readAsDataURL(file)
        const _this = this
        reader.onloadend = function (e) {
          _this.visible2 = true
          _this.loading2 = true
          _this.previewUrl = reader.result
          // _this.avatarUrl = reader.result
          // _this.uploadList = [file]
        }
      } else {
        this.$Message.error('请选择格式为png、jpg、jpeg的图片')
      }

      return false
    },
    avatarOk () {
      // file
      this.$refs.cropper.getCropData((data) => {
        this.avatarUrl = data
        this.uploadList = [this.dataURLtoFile(data, 'qq.jpg')]
        this.visible2 = false
      })
    },
    realTime (data) {
      var previews = data;
      var h = 0.5;
      var w = 0.2;
      this.previewStyle1 = {
        width: previews.w + "px",
        height: previews.h + "px",
        overflow: "hidden",
        margin: "0",
        zoom: h
      };

      this.previewStyle2 = {
        width: previews.w + "px",
        height: previews.h + "px",
        overflow: "hidden",
        margin: "0",
        zoom: w
      };
      this.previews = data;
    },
    // base 64 转file
    dataURLtoFile (dataurl, filename) {//将base64转换为文件
      var arr = dataurl.split(','), mime = arr[0].match(/:(.*?);/)[1],
        bstr = atob(arr[1]), n = bstr.length, u8arr = new Uint8Array(n);
      while (n--) {
        u8arr[n] = bstr.charCodeAt(n);
      }
      return new File([u8arr], filename, { type: mime });
    },
    showPassword () {
      if (this.inputType == 'password') {
        this.inputType = 'text'
        this.inputIcon = 'md-eye'
      } else {
        this.inputType = 'password'
        this.inputIcon = 'md-eye-off'
      }
    }
  },
  mounted () {
    this.formCustom = {
      password: this.password,
      passwdCheck: this.password,
      mobile: this.mobile,
      telephone: this.telephone,
      email: this.email,
      unit: this.unit,
      nativePlace: this.nativePlace,
      major: this.major,
      education: this.education,
      introduce: this.introduce,
      loginName: this.loginName
    }
    this.avatarUrl = this.avatorImgPath
  },
  computed: {
    ...mapState({
      hasGetInfo: state => state.user.hasGetInfo,
      userName: state => state.user.userName,
      userId: state => state.user.userId,
      avatorImgPath: state => state.user.avatorImgPath,
      roleName: state => state.user.roleName,
      roleId: state => state.user.roleId,
      mobile: state => state.user.mobile,
      name: state => state.user.name,
      no: state => state.user.no,
      email: state => state.user.email,
      password: state => state.user.password,
      unit: state => state.user.unit,
      nativePlace: state => state.user.nativePlace,
      major: state => state.user.major,
      education: state => state.user.education,
      introduce: state => state.user.introduce,
      loginName: state => state.user.loginName,
      telephone: state => state.user.telephone
    }),
  }
}
</script>
<style lang="scss">
#personal {
  display: flex;
  padding: 24px 32px;
  background: #fff;
  box-shadow: 0 4px 8px 0 rgba(7, 17, 27, 0.1);
  border-radius: 12px;
  .changeavatar {
    width: 120px;
    flex: 0 0 120px;
    text-align: center;
    .name-role {
      margin: 20px 0;
      display: flex;
      line-height: 20px;
      h3 {
        width: 50px;
        text-align: right;
      }
      h4 {
      }
    }
    img {
      width: 80px;
      height: 80px;
      border-radius: 100%;
    }
  }
  .info {
    flex: 1;
    .ivu-form {
      .regular {
        margin: 0;
      }
      .ivu-form-item {
        float: left;
        width: 50%;
      }
    }
  }
}
.cropper-content {
  display: flex;
  display: -webkit-flex;
  justify-content: flex-start;
  -webkit-justify-content: flex-start;
  .cropper {
    width: 300px;
    height: 300px;
    margin-right: 10px;
  }
  .show-preview {
    flex: 1;
    -webkit-flex: 1;
    display: flex;
    display: -webkit-flex;
    justify-content: center;
    -webkit-justify-content: center;
    .preview {
      overflow: hidden;
      border-radius: 50%;
      border: 1px solid #cccccc;
      background: #cccccc;
      margin-left: 40px;
    }
  }
}
</style>

